package servlet;

import domain.Student;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import service.StudentServiceImpl;
import util.TemplateEngineUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/selectStudentsServlet")
public class selectStudentsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        TemplateEngine engine= TemplateEngineUtil.getTemplateEngine(req.getServletContext());
        WebContext context = new WebContext(req, resp, req.getServletContext());
        resp.setCharacterEncoding("utf-8");

        //deliver student object to showUsername.html
        //req.setAttribute("student",student);
        List students=new ArrayList();
        try {
            //获取业务层对象
            StudentServiceImpl studentService=new StudentServiceImpl();
            //调用业务层对象studentService的getStudents方法，获得数据
            ResultSet rs=studentService.getStudents();
            //循环显示rs对象中的数据;rs.next()遍历指针
            Student student;
            while(rs.next())
            {
                //每一条记录，转变成一个Student对象
                student=new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setPassword(rs.getString("password"));
                student.setSex(rs.getInt("sex"));
                student.setClazz(rs.getString("clazz"));
                student.setBirthday(rs.getString("birthday"));
                //把student对象加入students列表
                students.add(student);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        //deliver students to showUsername.html
        req.setAttribute("students",students);

        engine.process("listStudents.html",context,resp.getWriter());
//         if(username.equals("admin")&&password.equals("admin"))
//             engine.process("success.html",context,resp.getWriter());
//         else
//             engine.process("index.html",context,resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
